package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;

import com.itheima.reggie.entity.*;

import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
//菜品管理
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;
    //新增菜品
    @PostMapping
    public R<String>save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto,0);
        return R.success("新增菜品成功");
    }
    //分页查询
    @GetMapping("/page")
    public R<Page>page (int page,int pageSize,String name){
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(name!=null,Dish::getName,name);

        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(dishPage,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        List<Dish> records = dishPage.getRecords();
        List<DishDto>list =records.stream().map((item)->{
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类ID
            //根据id查询分类对象
            Category byId = categoryService.getById(categoryId);
            String name1 = byId.getName();
            dishDto.setCategoryName(name1);
            return dishDto;

        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);

    }
    //根据id查询菜品信息和口味信息
    @GetMapping("/{id}")
    public R<DishDto>get(@PathVariable Long id){
        DishDto dishDto = dishService.useIdtoFlavor(id);

        return R.success(dishDto);
    }
    //修改菜品信息
    @PutMapping
    public R<String>update(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto,1);
        return R.success("修改成功");
    }
    //删除菜品 检查该菜品是否关联套餐，如果关联，则禁止删除
    @DeleteMapping
    public R<String>delete(@RequestParam("ids") List<Long> id){
       if(id.isEmpty()){
           return R.error("没有该菜品");
       }
       id.stream().forEach((item)->{
           //检查该菜品是否关联套餐，如果关联，则禁售套餐
           LambdaQueryWrapper<SetmealDish>queryWrapper = new LambdaQueryWrapper<>();
           queryWrapper.eq(SetmealDish::getDishId,item);
           int count = setmealDishService.count(queryWrapper);
           if(count > 0){
               String errorMsg = "有菜品在套餐内，禁止删除!";
               throw new CustomException(errorMsg);
           }

           dishService.deleteIdwithFlavor(item);
       });

       // log.info("id :   {}",id);
        return R.success("删除成功");
    }
    //停售菜品,检查该菜品是否关联套餐，如果关联，则禁售套餐
    @PostMapping("/status/{status}")
    public R<String>unsale(@PathVariable Integer status,@RequestParam("ids") List<Long> id){
        log.info("statis : {}     id:  {}",status,id);
        if(id.isEmpty() || status == null){
            return R.error("没有该菜品");
        }
        id.stream().forEach((item)->{
            Dish byId = dishService.getById(item);
            if (byId != null) {
                byId.setStatus(status);
                dishService.updateById(byId);
                if(status == 0){
                    //检查该菜品是否关联套餐，如果关联，则禁售套餐
                    LambdaQueryWrapper<SetmealDish>queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SetmealDish::getDishId,item);
                    List<SetmealDish> list = setmealDishService.list(queryWrapper);
                    log.info("item:     {}",item);

                    list.stream().forEach((item1)->{
                        Setmeal byId1 = setmealService.getById(item1.getSetmealId());
                        byId1.setStatus(0);
                        setmealService.updateById(byId1);
                    });
                }


            }

        });

        return R.success("修改成功");
    }

    //菜品分类
    /*@GetMapping("/list")
    public R<List<Dish>> list(Long categoryId) {
        log.info("cid:   {}", categoryId);
        if (categoryId == null) return R.error("错误");
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, categoryId);
        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId) {
        log.info("cid:   {}", categoryId);
        if (categoryId == null) return R.error("错误");
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, categoryId);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> listDto = list.stream().map((item)->{
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);
            Long categoryId1 = item.getCategoryId();//分类ID
            //根据id查询分类对象
            Category byId = categoryService.getById(categoryId1);
            String name1 = byId.getName();
            dishDto.setCategoryName(name1);

            //当前菜品ID
            Long dishId = item.getId();

            LambdaQueryWrapper<DishFlavor>dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;

        }).collect(Collectors.toList());


        return R.success(listDto);
    }





}
